package com.huidu.bitrade.aop;

import com.huidu.bitrade.constant.SysConstant;
import com.huidu.bitrade.entity.transform.AuthMember;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@Component
@Aspect
@RequiredArgsConstructor
public class NoRepeatSubmitAspect {

    private final RedisTemplate redisTemplate;

    @Pointcut("@annotation(repeatSubmit)")
    public void pointcutNoRepeat(NoRepeatSubmit repeatSubmit){};
    @Around(value = "pointcutNoRepeat(noRepeatSubmit)", argNames = "point,noRepeatSubmit")
    public Object doNoRepeat(ProceedingJoinPoint point, NoRepeatSubmit noRepeatSubmit) throws Throwable {
        int i=noRepeatSubmit.lockTime();
        HttpServletRequest httpServletRequest = HttpContextUtils.httpServletRequest();
        HttpSession session = httpServletRequest.getSession();
        AuthMember user = (AuthMember) session.getAttribute(SysConstant.SESSION_MEMBER);
        String url = httpServletRequest.getRequestURL().toString();
        String sign = url+"/"+user;
        Boolean key=redisTemplate.hasKey(sign);
        if (key){
            throw new IllegalArgumentException("请勿重复提交");
        }
        redisTemplate.opsForValue().set(sign,sign,i, TimeUnit.SECONDS);
        return  point.proceed();
    }
}
